<template>
	<view class="page__content">
		<!-- #ifndef MP-WEIXIN -->
		<u-navbar class="head" :fixed="false" :title="pageTitle" leftIconColor="#fff" :autoBack="true"
			:safeAreaInsetTop="true">
		</u-navbar>
		<!-- #endif -->




		<!-- web-view 组件 -->
		<web-view :src="webUrl" :update-title="false" @message="handleMessage" @load="handleLoad"
			@error="handleError"></web-view>

		<!-- 加载提示 -->
		<!-- <uni-loading-mask :show="isLoading" text="加载中..."></uni-loading-mask> -->

		<!-- 错误提示 -->
		<view v-if="errorMsg" class="error-container">
			<text class="error-text">{{ errorMsg }}</text>
			<button class="reload-btn" @click="reloadPage">重新加载</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, ref, nextTick, getCurrentInstance } from 'vue';
	import { onLoad, onShow, onReady } from '@dcloudio/uni-app'
	import { useMainStore, useInventoryStore, useUserStore, usePermissionStore } from '@/store';
	const inventoryStore = useInventoryStore();
	const mainStore = useMainStore();

	// 定义页面接收的参数类型
	interface WebViewOptions {
		url : string;
		title ?: string;
		// 导航栏配置
		navBgColor ?: string;    // 导航栏背景色
		navTextColor ?: string;  // 导航栏文字颜色
	}

	// 定义网页发送消息的类型
	interface WebMessage {
		action : 'close' | 'setTitle' | 'goBack' | string;
		title ?: string;
		[key : string] : any;
	}

	// 状态定义
	const webUrl = ref('');
	const pageTitle = ref('正在加载...');
	const isLoading = ref(true);
	const errorMsg = ref('');


	// 页面加载时处理参数
	onLoad((options : any) => {

		if (options.url) {
			webUrl.value = decodeURIComponent(options.url);
		} else {
			errorMsg.value = '缺少网页地址参数';
			isLoading.value = false;
		}

		// 处理标题
		if (options.title) {
			pageTitle.value = decodeURIComponent(options.title);
		}

		// 处理导航栏样式
		if (options.navBgColor || options.navTextColor) {
			setNavigationBarStyle({
				backgroundColor: decodeURIComponent(options.navBgColor) || '#F8F8F8',
				frontColor: decodeURIComponent(options.navTextColor) || '#000000'
			});
		}
	});


	// 获取当前页面的 webview 实例
	const pages = getCurrentPages()
	const page = pages[pages.length - 1]

	const getWebViewHeightFun = () => {
		uni.$utils.$uGetRect('.head').then((res : any) => {
			const { windowHeight } = mainStore.systemConfig.sysDeviceInfo;
			const targetWebview = page.$getAppWebview().children()[0];
			console.log(res.height);
			console.log(windowHeight);
			const offsetHeight = res.height;
			const bodyHeight = windowHeight - res.height;
			targetWebview.setStyle({ //设置web-view距离顶部的距离以及自己的高度，单位为px
				top: offsetHeight, //此处是距离顶部的高度，应该是你页面的头部
				height: bodyHeight, //webview的高度
			})

		});
	}

	onReady(() => {
		// 设置标题
		uni.setNavigationBarTitle({
			title: pageTitle.value || ""
		});


		// #ifndef MP-WEIXIN
		// 获取webview高度
		getWebViewHeightFun();
		// #endif


	});

	// 处理导航栏样式设置
	const setNavigationBarStyle = (options : {
		backgroundColor ?: string;
		frontColor ?: string;
	}) => {
		uni.setNavigationBarColor({
			backgroundColor: options.backgroundColor || '#F8F8F8',
			frontColor: options.frontColor || '#000000',
			animation: {
				duration: 300,
				timingFunc: 'easeInOut'
			}
		});
	};

	// 重新加载页面
	const reloadPage = () => {
		errorMsg.value = '';
		isLoading.value = true;
		// 添加时间戳防止缓存
		webUrl.value = webUrl.value + (webUrl.value.includes('?') ? '&' : '?') + `t=${new Date().getTime()}`;
	};

	// 接收网页发送的消息
	const handleMessage = (e : { detail : { data : WebMessage[] } }) => {
		console.log('收到网页消息:', e.detail.data);
		const message = e.detail.data[e.detail.data.length - 1];

		switch (message.action) {
			case 'close':
				break;
			case 'setTitle':
				if (message.title) {
					pageTitle.value = message.title;
					uni.setNavigationBarTitle({ title: message.title });
				}
				break;
			case 'goBack':
				uni.navigateBack();
				break;
			default:
				console.log('未处理的消息类型:', message.action);
		}
	};

	// 网页加载完成
	const handleLoad = () => {
		isLoading.value = false;
		console.log('网页加载完成');
	};

	// 网页加载失败
	const handleError = (e : any) => {
		isLoading.value = false;
		errorMsg.value = '网页加载失败，请稍后重试';
		console.error('网页加载错误:', e);
	};
</script>

<style scoped>
	.head {
		z-index: 99999999;
		position: relative;
	}

	.page__content {
		width: 100%;
		height: 100vh;
		overflow: hidden;
		position: relative;
	}

	.error-container {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		z-index: 5;
		padding: 20rpx;
	}

	.error-text {
		color: #f53f3f;
		font-size: 16px;
		margin-bottom: 30rpx;
	}

	.reload-btn {
		background-color: #007aff;
		color: #fff;
		border-radius: 8rpx;
		padding: 12rpx 30rpx;
		font-size: 14px;
	}
</style>